/* 
   学习目标：编辑文章路由匹配
*/
import React, { useEffect, useState } from 'react';
import { Breadcrumb, Card, Form, Radio, DatePicker, Table, Tag, Button, Modal } from 'antd';
import { Link } from 'react-router-dom';
import { delArticleByIdAPI, getArticleListAPI } from 'api/article';
import { EditOutlined } from '@ant-design/icons';
import { DeleteOutlined } from '@ant-design/icons';
import Channel from 'components/Channel';
const { RangePicker } = DatePicker;

const articleStatus = [
  { id: -1, name: '全部', color: 'magenta' },
  { id: 0, name: '草稿', color: 'orange' },
  { id: 1, name: '待审核', color: 'red' },
  { id: 2, name: '审核通过', color: 'green' },
  { id: 3, name: '审核失败', color: 'cyan' },
];

let formDataCache = {};
let pageDataCache = {};

export default function ArticleList(props) {
  const [listData, setListData] = useState({
    results: [],
    page: 1,
    total_count: 0,
    per_page: 10,
  });

  const loadList = async (params) => {
    const res = await getArticleListAPI(params);
    setListData(res.data);
  };

  useEffect(() => {
    loadList();
  }, []);

  useEffect(() => {
    // 卸载时清空缓存数据
    return () => {
      formDataCache = null;
      pageDataCache = null;
    };
  }, []);

  const handleFinish = (values) => {
    const begin_pubdate =
      values.date && values.date[0].startOf('day').format('YYYY-MM-DD HH:mm:ss');
    const end_pubdate = values.date && values.date[1].endOf('day').format('YYYY-MM-DD HH:mm:ss');
    let formValues = {
      ...values,
      begin_pubdate,
      end_pubdate,
    };

    delete formValues.date;

    if (formValues.status === -1) {
      delete formValues.status;
    }

    formValues = JSON.parse(JSON.stringify(formValues));

    formDataCache = { ...formValues };
    loadList({ ...formDataCache, ...pageDataCache });
  };

  const handlePageChange = (page, pageSize) => {
    pageDataCache = {
      page,
      per_page: pageSize,
    };
    loadList({
      page,
      per_page: pageSize,
      ...formDataCache,
    });
  };

  const handleDel = (id) => {
    Modal.confirm({
      title: '温馨提示',
      content: '你确定要删除这篇文章？',
      onOk: async () => {
        await delArticleByIdAPI(id);
        loadList({ ...formDataCache });
      },
    });
  };

  // 配置表格每一列如何显示
  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      render(cover) {
        return (
          <img
            src={cover.images[0]}
            alt=""
            width={100}
            height={60}
            style={{ objectFit: 'cover' }}
          />
        );
      },
      // React 需要的 key，如果已经设置了唯一的 dataIndex，可以忽略这个属性
      // key: 'name',
    },
    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render(status) {
        const tagInfo = articleStatus.find((item) => item.id === status);
        return <Tag color={tagInfo.color}>{tagInfo.name}</Tag>;
      },
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      key: 'action',
      render(_, rowData) {
        return (
          <>
            <Button
              shape="circle"
              type="primary"
              icon={<EditOutlined />}
              style={{ marginRight: 5 }}
              onClick={() => props.history.push('/edit/' + rowData.id)}
            ></Button>

            <Button
              shape="circle"
              danger
              icon={<DeleteOutlined />}
              onClick={() => handleDel(rowData.id)}
            ></Button>
          </>
        );
      },
    },
  ];

  return (
    <div className="articleList">
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>文章列表</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        {/* 4.  给表单设置初始值 */}
        <Form onFinish={handleFinish} initialValues={{ status: -1 }}>
          <Form.Item name="status" label="状态">
            <Radio.Group>
              <Radio value={-1}>全部</Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>审核通过</Radio>
              <Radio value={3}>审核失败</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item name="channel_id" label="频道">
            <Channel style={{ width: 200 }} allowClear></Channel>
          </Form.Item>

          <Form.Item name="date" label="日期">
            <RangePicker />
          </Form.Item>

          <Form.Item>
            <Button htmlType="submit" type="primary">
              筛选
            </Button>
          </Form.Item>
        </Form>
        <p>根据筛选条件共查询到 {listData.total_count} 条结果：</p>
        <Table
          rowKey="id"
          columns={columns}
          dataSource={listData.results}
          pagination={{
            onChange: handlePageChange,
            // 调整分页器的位置
            position: ['bottomCenter'],
            // 显示总条数
            total: listData.total_count,
            // 指定每页显示多少条数据
            pageSize: listData.per_page,
            // 指定当前页
            current: listData.page,
          }}
        />
      </Card>
    </div>
  );
}
